<script setup>
import {ref, onMounted} from "vue";
import {getList_Category} from "@/api/category";
import {add_Good} from "@/api/good";
import {ElMessage} from "element-plus";

const form = ref({
  name: '',
  description: '',
  imageUrl: '',
  price: '',
  stock: '',
  categoryId: '',
})
const handleChange = (response, file, fileList) => {
  //回调成功之后 修改表单的内容
  form.value.imageUrl = response.data.fileUrl;
  console.log(file)
}

const handleUpload = async () => {
  const res = await add_Good(form.value)
  if (res.code === 200) {
    ElMessage.success('添加成功');
    reset()
  }
}

const reset = () => {
  form.value={}
}
const category = ref([])
const init_category = async () => {
  const res = await getList_Category()
  category.value = res.data;
}
onMounted(() => {
  init_category()
})
</script>

<template>
  <div>
    <el-form label-width="auto" style="max-width: 600px">
      <el-form-item label="商品名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>

      <el-form-item label="商品描述">
        <el-input v-model="form.description"></el-input>
      </el-form-item>
      <el-form-item label="商品价格">
        <el-input v-model="form.price"></el-input>
      </el-form-item>
      <el-form-item label="商品库存">
        <el-input v-model="form.stock"></el-input>
      </el-form-item>

      <el-form-item label="商品的图片">
        <el-upload
            :auto-upload="true"
            action="/api/file/upload"
            accept=".png,.jpg"
            :on-success="handleChange"
            :limit="1"
            :show-file-list="true"
            ref="uploadForm"
        >
          <el-image v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
          </el-image>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>

      </el-form-item>

      <el-form-item label="商品的种类">
        <el-select v-model="form.categoryId" placeholder="选择商品分类">
          <el-option v-for="(item,index) in category "
                     :label="item.name" :value="item.id"
          >

          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <template #default>
          <el-button type="primary" @click="handleUpload">上传商品信息</el-button>
          <el-button type="primary">重置</el-button>
        </template>
      </el-form-item>
    </el-form>
  </div>

</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
